<template>
  <div class="course-container page-container">
    <div class="page-header">
      <h1 class="page-title">我的课程</h1>
      <div class="search-box">
        <el-input
          placeholder="搜索课程"
          prefix-icon="el-icon-search"
          v-model="searchKeyword"
          @keyup.enter.native="handleSearch"
          clearable
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 课程分类筛选 -->
    <div class="filter-section">
      <el-card shadow="never">
        <div class="filter-item">
          <span class="filter-label">学科:</span>
          <el-radio-group v-model="filters.subject" size="small" @change="handleFilterChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="subject in subjects" :key="subject.id" :label="subject.id">{{ subject.name }}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="filter-item">
          <span class="filter-label">难度:</span>
          <el-radio-group v-model="filters.level" size="small" @change="handleFilterChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">入门</el-radio-button>
            <el-radio-button label="2">初级</el-radio-button>
            <el-radio-button label="3">中级</el-radio-button>
            <el-radio-button label="4">高级</el-radio-button>
          </el-radio-group>
        </div>
      </el-card>
    </div>

    <!-- 课程列表 -->
    <div class="course-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in courseList" :key="course.id" class="course-item-col">
          <div class="blog-card course-card">
            <div class="course-cover">
              <img :src="course.cover" :alt="course.title">
              <div class="course-level" :class="`level-${course.level || 1}`">{{ getLevelText(course.level) }}</div>
            </div>
            <div class="blog-card-content">
              <h3 class="course-title">{{ course.title }}</h3>
              <p class="course-desc">{{ course.description || '暂无描述' }}</p>
              <div class="course-info">
                <div class="teacher-info">
                  <i class="el-icon-user"></i>
                  <span>{{ course.teacher }}</span>
                </div>
                <div class="course-meta">
                  <span><i class="el-icon-video-camera"></i> {{ course.chapterCount || 0 }}章</span>
                  <span><i class="el-icon-user"></i> {{ course.studentCount || 0 }}人学习</span>
                </div>
              </div>
            </div>
            <div class="blog-card-footer">
              <span class="course-progress" v-if="course.progress">
                学习进度: {{ course.progress }}%
                <el-progress :percentage="course.progress" :stroke-width="5"></el-progress>
              </span>
              <span class="course-progress" v-else>
                未开始学习
              </span>
              <router-link :to="`/course/${course.id}`" class="btn-primary">进入学习</router-link>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty v-if="courseList.length === 0 && !loading" description="暂无课程数据"></el-empty>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page.sync="currentPage"
          @current-change="handlePageChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getStudentCourses, searchCourses } from '@/api/course'
import { getAllSubjects } from '@/api/subject'

export default {
  name: 'CourseList',
  data() {
    return {
      courseList: [],
      loading: false,
      subjectLoading: false,
      currentPage: 1,
      pageSize: 12,
      total: 0,
      searchKeyword: '',
      filters: {
        subject: '',
        level: ''
      },
      subjects: []
    }
  },
  created() {
    this.fetchSubjects()
    this.fetchCourses()
  },
  methods: {
    // 获取学科列表
    fetchSubjects() {
      this.subjectLoading = true
      getAllSubjects()
        .then(response => {
          console.log('学科数据:', response) // 调试日志
          if (Array.isArray(response)) {
            this.subjects = response
          } else if (response && Array.isArray(response.records)) {
            this.subjects = response.records
          } else {
            this.subjects = []
          }
        })
        .catch(error => {
          console.error('获取学科列表失败:', error)
          this.$message.error('获取学科列表失败')
        })
        .finally(() => {
          this.subjectLoading = false
        })
    },
    fetchCourses() {
      this.loading = true
      
      // 确保所有参数都是简单类型，不要嵌套对象
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        keyword: this.searchKeyword,
        subject: this.filters.subject,
        level: this.filters.level,
        type: 'student'
      }
      
      console.log('发送的参数：', params) // 调试日志
      
      getStudentCourses(params)
        .then(response => {
          if (response && response.records) {
            this.courseList = response.records;
            this.total = response.total || 0;
            
            // 处理课程数据，添加缺失的字段
            this.courseList = this.courseList.map(course => {
              return {
                ...course,
                progress: Math.floor(Math.random() * 100),
                level: course.level || Math.floor(Math.random() * 4) + 1,
                description: course.description || '这是一门非常精彩的课程，包含丰富的教学内容和实践案例。',
                chapterCount: course.chapterCount || Math.floor(Math.random() * 20) + 5,
                studentCount: course.enrollCount || Math.floor(Math.random() * 1000) + 100,
                teacher: course.teacherName || `教师${course.teacherId}`
              }
            })
          } else {
            this.courseList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取课程列表失败:', error)
          this.$message.error('获取课程列表失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchCourses()
    },
    handlePageChange(page) {
      this.currentPage = page
      this.fetchCourses()
    },
    handleFilterChange() {
      this.currentPage = 1
      this.fetchCourses()
    },
    getLevelText(level) {
      const levels = {
        1: '入门',
        2: '初级',
        3: '中级',
        4: '高级'
      }
      return levels[level] || '入门'
    }
  }
}
</script>

<style lang="scss" scoped>
.course-container {
  padding-bottom: 40px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-item {
  margin-bottom: 15px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.filter-label {
  display: inline-block;
  width: 60px;
  color: #606266;
}

.course-item-col {
  margin-bottom: 20px;
}

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .course-cover {
    height: 160px;
    overflow: hidden;
    position: relative;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
    }
    
    .course-level {
      position: absolute;
      top: 10px;
      right: 10px;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 12px;
      color: white;
      background-color: rgba(0, 0, 0, 0.5);
      
      &.level-1 {
        background-color: #67C23A;
      }
      
      &.level-2 {
        background-color: #409EFF;
      }
      
      &.level-3 {
        background-color: #E6A23C;
      }
      
      &.level-4 {
        background-color: #F56C6C;
      }
    }
  }
  
  &:hover .course-cover img {
    transform: scale(1.05);
  }
  
  .blog-card-content {
    flex: 1;
  }
  
  .course-title {
    font-size: 18px;
    margin: 0 0 10px;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .course-desc {
    color: #606266;
    font-size: 14px;
    margin: 0 0 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    height: 42px;
  }
  
  .course-info {
    margin-top: 10px;
  }
  
  .teacher-info {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    
    i {
      margin-right: 5px;
      color: #909399;
    }
    
    span {
      color: #606266;
      font-size: 14px;
    }
  }
  
  .course-meta {
    display: flex;
    justify-content: space-between;
    color: #909399;
    font-size: 12px;
    
    span {
      display: flex;
      align-items: center;
      
      i {
        margin-right: 5px;
      }
    }
  }
  
  .course-progress {
    color: #606266;
    font-size: 14px;
  }
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-box {
    width: 100%;
    margin-top: 10px;
  }
  
  .filter-label {
    display: block;
    margin-bottom: 5px;
  }
}
</style> 